<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="search-page">
    <div class="search-container">
      <!-- 搜索头部 -->
      <div class="search-header">
        <div class="search-input-wrapper">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索剪纸文化、教程、资讯..."
            size="large"
            @keyup.enter="handleSearch"
            clearable
          >
            <template #append>
              <el-button @click="handleSearch" :icon="Search" />
            </template>
          </el-input>
        </div>
        
        <!-- 搜索筛选 -->
        <div class="search-filters">
          <el-radio-group v-model="activeTab" @change="handleTabChange">
            <el-radio-button label="all">全部</el-radio-button>
            <el-radio-button label="culture">文化</el-radio-button>
            <el-radio-button label="tutorial">教程</el-radio-button>
            <el-radio-button label="news">资讯</el-radio-button>
          </el-radio-group>
        </div>
      </div>

      <!-- 搜索结果 -->
      <div class="search-results" v-loading="loading">
        <!-- 搜索统计 -->
        <div class="search-stats" v-if="searchKeyword">
          <span>搜索 "{{ searchKeyword }}" 共找到 {{ totalResults }} 条结果</span>
        </div>

        <!-- 无结果 -->
        <div class="no-results" v-if="!loading && totalResults === 0 && searchKeyword">
          <el-empty description="没有找到相关内容">
            <el-button type="primary" @click="clearSearch">清空搜索</el-button>
          </el-empty>
        </div>

        <!-- 搜索结果列表 -->
        <div class="results-container" v-if="totalResults > 0">
          <!-- 文化内容结果 -->
          <div class="result-section" v-if="cultureResults.length > 0">
            <div class="section-title">
              <h3><el-icon><Collection /></el-icon> 剪纸文化</h3>
              <span class="count">{{ cultureResults.length }} 条结果</span>
            </div>
            <div class="culture-results">
              <div
                v-for="culture in cultureResults"
                :key="`culture-${culture.id}`"
                class="result-item culture-item"
                @click="$router.push(`/culture/${culture.id}`)"
              >
                <div class="result-image">
                  <img :src="culture.coverImage || '/default-culture.jpg'" :alt="culture.title" />
                </div>
                <div class="result-content">
                  <h4 v-html="highlightKeyword(culture.title)"></h4>
                  <p v-html="highlightKeyword(culture.summary || '')"></p>
                  <div class="result-meta">
                    <el-tag size="small" type="info">{{ getCategoryText(culture.category) }}</el-tag>
                    <span class="meta-item"><el-icon><View /></el-icon> {{ culture.viewCount }}</span>
                    <span class="meta-item"><el-icon><Star /></el-icon> {{ culture.likeCount }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 教程结果 -->
          <div class="result-section" v-if="tutorialResults.length > 0">
            <div class="section-title">
              <h3><el-icon><VideoPlay /></el-icon> 教程学习</h3>
              <span class="count">{{ tutorialResults.length }} 条结果</span>
            </div>
            <div class="tutorial-results">
              <div
                v-for="tutorial in tutorialResults"
                :key="`tutorial-${tutorial.id}`"
                class="result-item tutorial-item"
                @click="$router.push(`/tutorial/${tutorial.id}`)"
              >
                <div class="result-image">
                  <img :src="tutorial.coverImage || '/default-tutorial.jpg'" :alt="tutorial.title" />
                  <div class="difficulty-badge" :class="`level-${tutorial.difficultyLevel}`">
                    {{ getDifficultyText(tutorial.difficultyLevel) }}
                  </div>
                </div>
                <div class="result-content">
                  <h4 v-html="highlightKeyword(tutorial.title)"></h4>
                  <p v-html="highlightKeyword(tutorial.summary || '')"></p>
                  <div class="result-meta">
                    <el-tag size="small" type="success">{{ getTutorialCategoryText(tutorial.category) }}</el-tag>
                    <span class="meta-item"><el-icon><User /></el-icon> {{ tutorial.studyCount }}</span>
                    <span class="meta-item"><el-icon><Clock /></el-icon> {{ tutorial.estimatedTime }}min</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 资讯结果 -->
          <div class="result-section" v-if="newsResults.length > 0">
            <div class="section-title">
              <h3><el-icon><Bell /></el-icon> 活动资讯</h3>
              <span class="count">{{ newsResults.length }} 条结果</span>
            </div>
            <div class="news-results">
              <div
                v-for="news in newsResults"
                :key="`news-${news.id}`"
                class="result-item news-item"
                @click="$router.push(`/news/${news.id}`)"
              >
                <div class="result-image">
                  <img :src="news.coverImage || '/default-news.jpg'" :alt="news.title" />
                </div>
                <div class="result-content">
                  <h4 v-html="highlightKeyword(news.title)"></h4>
                  <p v-html="highlightKeyword(news.summary || '')"></p>
                  <div class="result-meta">
                    <el-tag size="small" type="warning">{{ getNewsTypeText(news.type) }}</el-tag>
                    <span class="meta-item"><el-icon><Calendar /></el-icon> {{ formatDate(news.createTime) }}</span>
                    <span class="meta-item"><el-icon><View /></el-icon> {{ news.viewCount }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 加载更多 -->
        <div class="load-more" v-if="hasMore && totalResults > 0">
          <el-button @click="loadMore" :loading="loadingMore">加载更多</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  Search, Collection, VideoPlay, Bell, View, Star, User, Clock, Calendar 
} from '@element-plus/icons-vue'
import { cultureApi, tutorialApi, newsApi } from '@/api'
import type { Culture, Tutorial, News } from '@/types/common'
import { CULTURE_CATEGORIES, TUTORIAL_CATEGORIES, TUTORIAL_DIFFICULTY, NEWS_TYPES } from '@/types/common'

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const loadingMore = ref(false)
const searchKeyword = ref('')
const activeTab = ref('all')

const cultureResults = ref<Culture[]>([])
const tutorialResults = ref<Tutorial[]>([])
const newsResults = ref<News[]>([])

const currentPage = ref(1)
const pageSize = ref(10)
const hasMore = ref(false)

// 初始化方法
const initializeData = () => {
  console.log('初始化搜索数据')
  cultureResults.value = []
  tutorialResults.value = []
  newsResults.value = []
  currentPage.value = 1
  hasMore.value = false
}

// 计算属性
const totalResults = computed(() => {
  const cultureCount = cultureResults.value?.length || 0
  const tutorialCount = tutorialResults.value?.length || 0
  const newsCount = newsResults.value?.length || 0
  return cultureCount + tutorialCount + newsCount
})

// 搜索方法
const searchCulture = async (keyword: string, page = 1) => {
  try {
    console.log('搜索文化内容:', { keyword, page, pageSize: pageSize.value })
    // 使用列表API，它支持所有查询参数
    const response = await cultureApi.getCulturePage({
      keyword,
      page,
      size: pageSize.value
    })
    console.log('文化内容搜索响应:', response)
    return response.data || { records: [], total: 0 }
  } catch (error) {
    console.error('搜索文化内容失败:', error)
    return { records: [], total: 0 }
  }
}

const searchTutorials = async (keyword: string, page = 1) => {
  try {
    console.log('搜索教程:', { keyword, page, pageSize: pageSize.value })
    // 使用列表API，它支持所有查询参数
    const response = await tutorialApi.getTutorialPage({
      keyword,
      page,
      size: pageSize.value
    })
    console.log('教程搜索响应:', response)
    return response.data || { records: [], total: 0 }
  } catch (error) {
    console.error('搜索教程失败:', error)
    return { records: [], total: 0 }
  }
}

const searchNews = async (keyword: string, page = 1) => {
  try {
    console.log('搜索资讯:', { keyword, page, pageSize: pageSize.value })
    // 使用列表API，它支持所有查询参数
    const response = await newsApi.getNewsPage({
      keyword,
      page,
      size: pageSize.value
    })
    console.log('资讯搜索响应:', response)
    return response.data || { list: [], total: 0 }
  } catch (error) {
    console.error('搜索资讯失败:', error)
    return { list: [], total: 0 }
  }
}

// 执行搜索
const handleSearch = async (resetPage = true) => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }

  if (resetPage) {
    currentPage.value = 1
    cultureResults.value = []
    tutorialResults.value = []
    newsResults.value = []
  }

  loading.value = true

  try {
    const keyword = searchKeyword.value.trim()
    
    if (activeTab.value === 'all' || activeTab.value === 'culture') {
      const cultureData = await searchCulture(keyword, currentPage.value)
      if (resetPage) {
        cultureResults.value = cultureData.records || []
      } else {
        cultureResults.value.push(...(cultureData.records || []))
      }
    }

    if (activeTab.value === 'all' || activeTab.value === 'tutorial') {
      const tutorialData = await searchTutorials(keyword, currentPage.value)
      if (resetPage) {
        tutorialResults.value = tutorialData.records || []
      } else {
        tutorialResults.value.push(...(tutorialData.records || []))
      }
    }

    if (activeTab.value === 'all' || activeTab.value === 'news') {
      const newsData = await searchNews(keyword, currentPage.value)
      if (resetPage) {
        newsResults.value = newsData.list || []
      } else {
        newsResults.value.push(...(newsData.list || []))
      }
    }

    // 更新URL
    router.push({ query: { keyword: keyword, tab: activeTab.value } })
  } catch (error) {
    ElMessage.error('搜索失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 处理标签页切换
const handleTabChange = () => {
  if (searchKeyword.value.trim()) {
    handleSearch(true)
  }
}

// 加载更多
const loadMore = () => {
  currentPage.value++
  loadingMore.value = true
  handleSearch(false).finally(() => {
    loadingMore.value = false
  })
}

// 清空搜索
const clearSearch = () => {
  searchKeyword.value = ''
  cultureResults.value = []
  tutorialResults.value = []
  newsResults.value = []
  router.push('/search')
}

// 高亮关键词
const highlightKeyword = (text: string) => {
  if (!searchKeyword.value || !text) return text
  const regex = new RegExp(`(${searchKeyword.value})`, 'gi')
  return text.replace(regex, '<mark>$1</mark>')
}

// 获取分类文本
const getCategoryText = (category: number) => {
  return CULTURE_CATEGORIES[category as keyof typeof CULTURE_CATEGORIES] || '其他'
}

const getTutorialCategoryText = (category: number) => {
  return TUTORIAL_CATEGORIES[category as keyof typeof TUTORIAL_CATEGORIES] || '其他'
}

const getDifficultyText = (level: number) => {
  return TUTORIAL_DIFFICULTY[level as keyof typeof TUTORIAL_DIFFICULTY] || '未知'
}

const getNewsTypeText = (type: number) => {
  return NEWS_TYPES[type as keyof typeof NEWS_TYPES] || '其他'
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 监听路由变化
watch(() => route.query, (newQuery) => {
  if (newQuery.keyword) {
    searchKeyword.value = newQuery.keyword as string
    activeTab.value = (newQuery.tab as string) || 'all'
    if (searchKeyword.value) {
      handleSearch(true)
    }
  }
}, { immediate: true })

onMounted(() => {
  // 初始化数据
  initializeData()
  
  // 从URL获取搜索参数
  if (route.query.keyword) {
    searchKeyword.value = route.query.keyword as string
    activeTab.value = (route.query.tab as string) || 'all'
    handleSearch(true)
  }
})
</script>

<style scoped>
.search-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.search-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.search-header {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.search-input-wrapper {
  margin-bottom: 20px;
}

.search-filters {
  display: flex;
  justify-content: center;
}

.search-stats {
  margin-bottom: 20px;
  color: #666;
  font-size: 14px;
}

.no-results {
  background: #fff;
  border-radius: 12px;
  padding: 40px;
  text-align: center;
}

.results-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.result-section {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #f0f0f0;
}

.section-title h3 {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  display: flex;
  align-items: center;
  gap: 8px;
}

.count {
  color: #666;
  font-size: 14px;
}

.culture-results,
.tutorial-results,
.news-results {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.result-item {
  display: flex;
  padding: 16px;
  border-radius: 8px;
  transition: all 0.3s;
  cursor: pointer;
  border: 1px solid #f0f0f0;
}

.result-item:hover {
  background: #f9f9f9;
  border-color: #d32f2f;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.result-image {
  position: relative;
  width: 120px;
  height: 80px;
  border-radius: 6px;
  overflow: hidden;
  flex-shrink: 0;
  margin-right: 16px;
}

.result-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.difficulty-badge {
  position: absolute;
  top: 4px;
  right: 4px;
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 10px;
  font-weight: bold;
  color: #fff;
}

.difficulty-badge.level-1 {
  background: #4caf50;
}

.difficulty-badge.level-2 {
  background: #ff9800;
}

.difficulty-badge.level-3 {
  background: #f44336;
}

.result-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.result-content h4 {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
  line-height: 1.4;
}

.result-content h4 :deep(mark) {
  background: #fff3cd;
  color: #856404;
  padding: 0 2px;
}

.result-content p {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
  line-height: 1.5;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.result-content p :deep(mark) {
  background: #fff3cd;
  color: #856404;
  padding: 0 2px;
}

.result-meta {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-top: auto;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #999;
}

.load-more {
  text-align: center;
  margin-top: 24px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-container {
    padding: 16px;
  }

  .search-header {
    padding: 20px;
  }

  .result-item {
    flex-direction: column;
  }

  .result-image {
    width: 100%;
    height: 120px;
    margin-right: 0;
    margin-bottom: 12px;
  }

  .section-title {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
</style>
